package com.fishleap.discovery;

import com.fishleap.loadbalance.LoadBalance;
import com.fishleap.loadbalance.RandomLoadBalance;
import com.fishleap.util.CuratorUtils;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zlg
 * 使用Zookeeper进行服务查找
 */
@Slf4j
public class ZkServiceDiscovery implements ServiceDiscovery {
    private final LoadBalance loadBalance;

    public ZkServiceDiscovery() {
        // 随机负载均衡算法
        loadBalance = new RandomLoadBalance();
    }

    // 随机与单台服务器建立连接
    @Override
    public InetSocketAddress lookupService(String serviceName) {
        List<String> childrenNodes = CuratorUtils.getChildrenNodes(serviceName);
        // 采用随机算法
        String targetServiceUrl = loadBalance.selectServiceAddress(childrenNodes);
        // eg:127.0.0.1:8888
        log.info("成功找到服务器地址: [{}]", targetServiceUrl);
        String[] split = targetServiceUrl.split(":");
        // host:port
        return new InetSocketAddress(split[0],Integer.parseInt(split[1]));
    }

    // 与所有服务器建立连接
    @Override
    public List<String> lookupServiceAll(String serviceName) {
        List<InetSocketAddress> list = new ArrayList<>();
        List<String> childrenNodes = CuratorUtils.getChildrenNodes(serviceName);
        /*childrenNodes.forEach(i -> {
            String[] split = i.split(":");
            InetSocketAddress inetSocketAddress = new InetSocketAddress(split[0], Integer.parseInt(split[1]));
            list.add(inetSocketAddress);
        });*/
        return childrenNodes;
    }
}
